package com.gitee.chessboard.properties;

import com.gitee.chessboard.annotation.DictionaryScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Set;

/**
 * 读取启动类上的扫描路径
 *
 * @author 敲代码的旺财
 * @date 2021/12/14 10:05
 */
@Order(Ordered.LOWEST_PRECEDENCE)
public class DictionaryEnvironment implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String scan = getScan(application);
        environment.getSystemProperties().put(DictionaryProperties.dictionaryScan,scan);
    }

    private String getScan(SpringApplication application){
        Set<Object> allSources = application.getAllSources();
        for (Object allSource : allSources) {
            if (!(allSource instanceof Class)){
                continue;
            }
            DictionaryScan annotation = ((Class<?>)allSource).getDeclaredAnnotation(DictionaryScan.class);
            if (annotation != null && annotation.value().length() > 0){
                return annotation.value();
            }
        }
        throw new RuntimeException("无法查询到扫描路径，请检查DictionaryScan注解");
    }
}
